//
//  ViewController.m
//  卡片CollectionVIew
//
//  Created by 栗子 on 2017/8/16.
//  Copyright © 2017年 http://www.cnblogs.com/Lrx-lizi/. All rights reserved.
//

#import "ViewController.h"
#import "CardCollectionVIewLayout.h"
#import "CardCollectionViewCell.h"
#import "Healp.h"
#import "Header.h"
#import "YSHYSlideViewController.h"
#import "ListModel.h"
#import "XHToast.h"
#import "ListViewVC.h"

#define ITEMCELLID  @"ITEMCELLID"
#define LZScreenW [UIScreen mainScreen].bounds.size.width
#define LZScreenH [UIScreen mainScreen].bounds.size.height

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    UIImageView      *bgImageV;
    UICollectionView *cardCollectionVIew;
    
    CGFloat          startX;
    CGFloat          endX;
    NSInteger        currentIndex;
    
}
@property (nonatomic, strong) NSMutableArray *sourceList;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) NSMutableArray *selArray;        // 储存选中的item
@property (nonatomic, strong) NSString *collectionJudge;

@end

@implementation ViewController

- (void)viewWillAppear:(BOOL)animated {
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self getContenList];
    _collectionJudge = @"no";
}

- (NSMutableArray *)selArray {
    if (!_selArray) {
        _selArray = [NSMutableArray new];
    }
    return _selArray;
}

- (NSMutableArray *)sourceList {
    if (!_sourceList) {
        _sourceList = [NSMutableArray new];
    }
    return _sourceList;
}

- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray new];
    }
    return _imageArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    //设置导航栏背景图片为一个空的image，这样就透明了
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    
    //去掉透明后导航栏下边的黑边
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];

    
    //imageArray = @[@"BACKGROUND",@"BACKGROUND",@"BACKGROUND",@"BACKGROUND",@"5.jpg",@"6.jpg",@"7.jpg",@"8.jpg"];
    
    //创建视图
    [self createUI];
    
}

-(void)createUI{
    
    bgImageV  = [[UIImageView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:bgImageV];
    bgImageV.image = [UIImage imageNamed:@"BACKGROUND"];
    [Healp blurEffect:bgImageV];//设置毛玻璃效果
    
    CardCollectionVIewLayout *layout = [[CardCollectionVIewLayout alloc]init];
    cardCollectionVIew  = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, LZScreenW, LZScreenH) collectionViewLayout:layout];
    [self.view addSubview:cardCollectionVIew];
    cardCollectionVIew.delegate=self;
    cardCollectionVIew.dataSource=self;
    cardCollectionVIew.backgroundView=bgImageV;
    cardCollectionVIew.showsHorizontalScrollIndicator=NO;
    [cardCollectionVIew registerClass:[CardCollectionViewCell class] forCellWithReuseIdentifier:ITEMCELLID];
    
    UIButton *back=[[UIButton alloc]init];
    UIImage *img=[UIImage imageNamed:@"Chevron"];
    [back setImage:img forState:UIControlStateNormal];
    //    back.frame=CGRectMake(0, 0, 12.5, 21);
    [back addTarget:self action:@selector(toIndexView) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *left=[[UIBarButtonItem alloc]initWithCustomView:back];
    self.navigationItem.leftBarButtonItem=left;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _imageArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CardCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ITEMCELLID forIndexPath:indexPath];
    __weak typeof(cell)weakCell = cell;
    NSLog(@"%@",self.sourceList[indexPath.item]);
    ListModel *model = self.sourceList[indexPath.item];
    WS(weakSelf);
    cell.collectionAction = ^{
         if ([weakSelf.selArray containsObject:indexPath]) {
             [weakCell.collectionButton setImage:[UIImage imageNamed:@"Imported Layers Copy-1"] forState:UIControlStateNormal];
             [weakSelf.selArray removeObject:indexPath];
             [weakSelf deleteCollection:indexPath.row];
         }
         else {
             if (![model.collectionId isEqualToString:@"a"]) {
                 [weakCell.collectionButton setImage:[UIImage imageNamed:@"Imported Layers Copy-1"] forState:UIControlStateNormal];
                 [weakSelf deleteCollection:indexPath.row];
            
             }
             else{
                 [weakCell.collectionButton setImage:[UIImage imageNamed:@"Imported Layers Copy 2"] forState:UIControlStateNormal];
                 [weakSelf.selArray addObject:indexPath];
                 [weakSelf addCollection:indexPath.row];
             }
             
         }

    };
    
    if ([weakSelf.selArray containsObject:indexPath]) {
        [weakCell.collectionButton setImage:[UIImage imageNamed:@"Imported Layers Copy 2"] forState:UIControlStateNormal];
    }
    else if (![model.collectionId isEqualToString:@"a"]){
        [weakCell.collectionButton setImage:[UIImage imageNamed:@"Imported Layers Copy 2"] forState:UIControlStateNormal];
    }
    else {
        [weakCell.collectionButton setImage:[UIImage imageNamed:@"Imported Layers Copy-1"] forState:UIControlStateNormal];
    }
    
    cell.imageIV.image=[UIImage imageNamed:[NSString stringWithFormat:@"%@",_imageArray[indexPath.row]]];

    [cell setCellValue:model];
    return cell;
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    startX = scrollView.contentOffset.x;
    
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    endX = scrollView.contentOffset.x;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self cellToCenter];
    });
}
-(void)cellToCenter{
        //最小滚动距离
    float  dragMinDistance = cardCollectionVIew.bounds.size.width/20.0f;
    if (startX - endX >= dragMinDistance) {
        currentIndex -= 1; //向右
    }else if (endX - startX >= dragMinDistance){
        currentIndex += 1 ;//向左
    }
    NSInteger maxIndex  = [cardCollectionVIew numberOfItemsInSection:0] - 1;
    currentIndex = currentIndex <= 0 ? 0 :currentIndex;
    currentIndex = currentIndex >= maxIndex ? maxIndex : currentIndex;
    
    bgImageV.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",_imageArray[currentIndex]]];
    
    [cardCollectionVIew scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    
}

-(void)toIndexView{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//获取表单
- (void)getContenList {
    [SVProgressHUD showWithStatus:@"loading"];
    [self.sourceList removeAllObjects];
    [self.imageArray removeAllObjects];
    AFHTTPSessionManager* session=[AFHTTPSessionManager manager];
    session.responseSerializer=[AFHTTPResponseSerializer serializer];
    [session GET:@"http://127.0.0.1:3000/list" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        NSLog(@"下载成功");
        id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *arr = (NSMutableArray *)jsonObject;
        NSLog(@"%@",arr);
       
        for (NSDictionary *dic in arr) {
            
            ListModel *model = [ListModel mj_objectWithKeyValues:dic];
            [self.imageArray addObject:model.backImage];
            [self.sourceList addObject:model];
        }
        [cardCollectionVIew reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [XHToast showCenterWithText:@"请求错误"];
    }];
}

//添加收藏
- (void)addCollection:(NSInteger )row  {
    
    ListModel *model = [ListModel new];
    model = self.sourceList[row];
    NSDictionary *parameters = @{@"id":model.id, @"userId":[[NSUserDefaults standardUserDefaults] valueForKey:USERID]};
    AFHTTPSessionManager* session=[AFHTTPSessionManager manager];
    session.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    [session POST:@"http://127.0.0.1:3000/collection" parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [XHToast showCenterWithText:@"收藏成功"];
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
        
    }];
}

//取消收藏
- (void)deleteCollection:(NSInteger )row  {
    
    ListModel *model = [ListModel new];
    model = self.sourceList[row];
    NSDictionary *parameters = @{@"id":model.id, @"userId":@"a"};
    AFHTTPSessionManager* session=[AFHTTPSessionManager manager];
    session.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    [session POST:COLLECTION parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [XHToast showCenterWithText:@"取消收藏"];
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
    }];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ListViewVC *vc = [ListViewVC new];
    vc.listOrTask = 1;
    vc.model = self.sourceList[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}


@end
